<?php

namespace App\Remote\Tiger\OrganizationManage;

use App\Exceptions\BaseException;
use App\Kuafu\Config\Model\ConfigModel;
use App\Remote\Tiger\Remote;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\HttpFoundation\Request as RequestAlias;

class OrganizationManageRemote extends Remote
{
    /**
     * 获取用户组织
     *
     * @param int $uid
     * @return mixed|void
     * @throws BaseException
     * @throws GuzzleException
     */
    public static function userOrganization(int $uid)
    {
        return self::customCacheRequest(
            "internal/openShop/organizationManage/userOrganization",
            RequestAlias::METHOD_GET,
            ["uid" => $uid],
            null,
            6 * 10
        );
    }

    /**
     * 组织管理列表 | 用户组织管理列表
     *
     * @param int|null $uid
     * @return mixed
     * @throws BaseException
     * @throws GuzzleException
     */
    public static function organizationManageList(int $uid = null): array
    {
        $cacheConfigModel       = ConfigModel::query()
                                             ->where("type", "cache")
                                             ->where("key", "organizationManageCacheTime")
                                             ->first();
        $cacheTime              = $cacheConfigModel ? $cacheConfigModel->getAttribute("value") : 0;
        $organizationManageList = self::customCacheRequest(
            "internal/openShop/organizationManage/list",
            RequestAlias::METHOD_GET,
            null,
            null,
            $cacheTime,
            vsprintf("%s:%s:%s", [
                "REMOTE:2023:03:19",
                collect(explode("\\", __CLASS__))->last(),
                __FUNCTION__
            ])
        );

        return is_int($uid) && $uid > 0 ? (function (int $uid, array $organizationManageList) {

            $organizationIds = [];
            // todo 判断战区权限
            $warZoneGroup = collect($organizationManageList["warZone"] ?? []);
            $warZoneGroup->each(function ($warZone) use ($uid, &$organizationIds) {
                $isCharge = collect($warZone["regionUserMapping"])->where("userId", $uid)->count();
                if ($isCharge) {
                    $organizationIds = array_merge(
                        $organizationIds, collect($warZone["regionMapping"])->pluck("manageId")->toArray()
                    );
                }
            });

            $all          = false;
            $branch       = [];
            $provinceCode = [];
            $cityCode     = [];
            $districtCode = [];
            $shopIds      = [];
            collect($organizationManageList["organizationManageList"])->each(function ($v) use (
                $uid,
                &$all,
                &$branch,
                &$provinceCode,
                &$cityCode,
                &$districtCode,
                $organizationIds,
                &$shopIds
            ) {
                if (
                    $v["operationUid"] == $uid
                    ||
                    in_array($v["id"], $organizationIds)
                    ||
                    collect($v["operationAttacheUser"])->where("uid", $uid)->count() > 0
                ) {
                    if ($v["type"] == 1) {
                        $all = true;
                        return false;
                    } else {
                        array_push($branch, $v["name"]);
                        $provinceCode = array_merge(
                            $provinceCode,
                            array_column($v["provonceManagerGroup"] ?? [], "provinceCode")
                        );
                    }
                }

                // 督导
                collect($v["growManagerGroup"])->where("userId", $uid)->each(function ($v) use (
                    &$districtCode,
                    &$shopIds
                ) {

                    // 督导 不返回区域 只有关联门店
//                    collect($v["addressCodes"])->each(function ($v) use (&$districtCode) {
//                        $addressCodesArr = explode("-", $v);
//                        array_push($districtCode, $addressCodesArr[2]);
//                    });

                    if (isset($v['shopIds']) && $v['shopIds']) {
                        $shopIds = array_unique(array_merge($shopIds, $v['shopIds']));// 督导关联门店id
                    }
                });

                // 城市经理 - 运营城市经理
                collect($v["cityManagerGroup"])->where("userId", $uid)->each(function ($v) use (&$cityCode) {
                    collect($v["addressCodes"])->each(function ($v) use (&$cityCode) {
                        $addressCodesArr = explode("-", $v);
                        array_push($cityCode, $addressCodesArr[1]);
                    });
                });

                // 开发城市经理
                if (isset($v['developCityManagerGroup']) && $v['developCityManagerGroup']) {
                    collect($v['developCityManagerGroup'])->where('userId', $uid)->each(function ($v) use (&$cityCode) {
                        collect($v['addressCodes'])->each(function ($v) use (&$cityCode) {
                            $addressCodesArr = explode('-', $v);
                            array_push($cityCode, $addressCodesArr[1]);
                        });
                    });
                }

            });

            return [
                "all"          => $all,
                "branch"       => $branch,
                "provinceCode" => $provinceCode,
                "cityCode"     => $cityCode,
                "districtCode" => $districtCode,
                'shopIds'      => $shopIds,
            ];

        })($uid, $organizationManageList) : $organizationManageList;
    }
}
